package daytrader.framework;
import java.lang.Math;

import daytrader.types.Stock;
import daytrader.types.Hold;
import daytrader.types.Portfolio;
import daytrader.lib.LibDataInterface;
import daytrader.lib.MockLibData;
import daytrader.strategy.BuyStrategy;
import daytrader.strategy.SellStrategy;

public class MockEngine implements EngineStrategyInterface {
   static final double PROFIT = 0.00;
   static final double LOSS = 0.00;
   static final double RISE = 0.00;
   static final double FALL = 0.00;
   LibDataInterface libData;
   Portfolio portfolio;
   private Stock current;
   BuyStrategy buy;
   SellStrategy sell;
   
   MockEngine() {
      libData = new MockLibData();
      portfolio = new Portfolio();
      buy = new BuyStrategy(this);
      sell = new SellStrategy(this);
   }
   public void runBuy() {
      buy.run();
   }
   public void runSell() {
      sell.run();
   }
   public void setCurrent(Stock current) {
          this.current = current;
          libData.openStockFeed(current);
  }
   public void setCurrent(Hold current) {
          Stock stock = current.stock;
          stock.hid = current.id;
          this.current = stock;
          libData.openStockFeed(stock);
   }
   public Stock getCurrent() {
      Stock ret = new Stock(MockLibData.STOCKNAME);
      return ret;
   }
   public LibDataInterface getLibData() {
      return libData;
   }
   public double getProfit() {
      return PROFIT;
   }
   public double getLoss() {
      return LOSS;
   }
   public double getRise() {
      return RISE;
   }
   public double getFall() {
      return FALL;
   }
   public Portfolio getPortfolio() {
      return portfolio;
   }
   public void buy(int unit) {
      if (unit < 0)
         return;
      Hold hold = new Hold(getCurrent(), unit, libData.close());
      portfolio.stocks.add(hold);
   }
   private Hold getCurrentHold() {
         Hold ch = null;
         // find the current hold by checking ids.
         for (Hold hold: portfolio.stocks) {
             if (hold.id == current.hid) {
                ch = hold;
                break;
             }
         }
         return ch;
   }
   public void sell(int unit) {
      if (unit < 0)
         return;
      Hold ch = getCurrentHold();
      if (ch==null) {
         System.err.println("[DayTrayder::sell] No such current Hold.");
         return;
      }
      dosell(ch, unit);
   }

     private void dosell(Hold ch, int unit) {
         unit = Math.min(ch.amount, unit);
         double currClosePrice = libData.close();
         double money = (double) unit * currClosePrice;
         ch.amount -= unit;
         if (ch.amount == 0) {
             int index = portfolio.stocks.indexOf(ch);
             portfolio.stocks.remove(index);
         }
     }

   public static void main (String [] args)
   {
      MockEngine engine = new MockEngine();
      engine.runBuy();
      engine.runSell();
   }

}

